"""
缺陷相关数据模型
用于数据库存储的模型定义
"""
from typing import Optional, List, Dict, Any, TYPE_CHECKING
from datetime import datetime
from enum import Enum
from pydantic import BaseModel, Field
from bson import ObjectId
from app.models.base import PyObjectId

if TYPE_CHECKING:
    from app.schemas.defect import DefectCommentResponse, DefectAttachmentResponse

# 缺陷状态通过state模块进行管理，使用字符串类型

class DefectPriority(str, Enum):
    """缺陷优先级枚举"""
    LOWEST = "lowest"              # 最低
    LOW = "low"                    # 低
    MEDIUM = "medium"              # 中
    HIGH = "high"                  # 高
    URGENT = "urgent"              # 紧急
    CRITICAL = "critical"          # 严重
    BLOCKER = "blocker"            # 阻塞


class DefectSeverity(str, Enum):
    """缺陷严重程度枚举"""
    TRIVIAL = "trivial"            # 轻微
    MINOR = "minor"                # 次要
    MAJOR = "major"                # 主要
    IMPORTANT = "important"        # 重要
    CRITICAL = "critical"          # 严重
    URGENT = "urgent"              # 紧急
    BLOCKER = "blocker"            # 阻塞


class DefectType(str, Enum):
    """缺陷类型枚举"""
    FUNCTIONAL = "functional"      # 功能缺陷
    UI = "ui"                      # 界面缺陷
    PERFORMANCE = "performance"    # 性能问题
    SECURITY = "security"          # 安全问题
    COMPATIBILITY = "compatibility" # 兼容性问题
    USABILITY = "usability"        # 易用性问题
    DATA = "data"                  # 数据问题
    INTEGRATION = "integration"    # 集成问题
    CONFIGURATION = "configuration" # 配置问题
    DOCUMENTATION = "documentation" # 文档问题


class DefectSource(str, Enum):
    """缺陷来源枚举"""
    TESTING = "testing"            # 测试
    PRODUCTION = "production"      # 生产环境
    CODE_REVIEW = "code_review"    # 代码审查
    USER_FEEDBACK = "user_feedback" # 用户反馈
    MONITORING = "monitoring"      # 监控发现
    INTERNAL = "internal"          # 内部发现
    EXTERNAL = "external"          # 外部发现


class DefectEnvironmentInfo(BaseModel):
    """缺陷环境信息模型"""
    os: Optional[str] = Field(None, description="操作系统")
    browser: Optional[str] = Field(None, description="浏览器")
    version: Optional[str] = Field(None, description="版本")
    device: Optional[str] = Field(None, description="设备")
    resolution: Optional[str] = Field(None, description="分辨率")
    additional_info: Optional[Dict[str, Any]] = Field(None, description="其他信息")


class DefectBase(BaseModel):
    """缺陷基础模型"""
    title: str = Field(..., min_length=1, max_length=200, description="缺陷标题")
    description: Optional[str] = Field(None, description="缺陷描述")
    type: DefectType = Field(..., description="缺陷类型")
    status: str = Field(default="", description="缺陷状态（从状态管理系统动态获取，创建时使用默认状态）")
    priority: DefectPriority = Field(DefectPriority.MEDIUM, description="优先级")
    severity: DefectSeverity = Field(DefectSeverity.MINOR, description="严重程度")
    source: DefectSource = Field(..., description="缺陷来源")
    project_id: Optional[str] = Field(None, description="关联项目ID")
    assignee_id: Optional[str] = Field(None, description="负责人ID")
    reporter_id: Optional[str] = Field(None, description="报告人ID")
    verifier_id: Optional[str] = Field(None, description="验证人ID")
    steps_to_reproduce: Optional[str] = Field(None, description="复现步骤")
    expected_result: Optional[str] = Field(None, description="预期结果")
    actual_result: Optional[str] = Field(None, description="实际结果")
    environment_info: Optional[DefectEnvironmentInfo] = Field(None, description="环境信息")
    found_date: Optional[datetime] = Field(None, description="发现时间")
    completed_at: Optional[datetime] = Field(None, description="完成时间")
    actual_completed_at: Optional[datetime] = Field(None, description="实际完成时间")
    tags: List[str] = Field(default_factory=list, description="标签")
    organization_id: Optional[str] = Field(None, description="组织ID")


class DefectInDB(DefectBase):
    """数据库中的缺陷模型"""
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    comments: List[Dict[str, Any]] = Field(default_factory=list, description="评论列表")
    attachments: List[Dict[str, Any]] = Field(default_factory=list, description="附件列表")
    resolved_date: Optional[datetime] = Field(None, description="解决时间")
    verified_date: Optional[datetime] = Field(None, description="验证时间")
    completed_at: Optional[datetime] = Field(None, description="完成时间")
    actual_completed_at: Optional[datetime] = Field(None, description="实际完成时间")
    created_by: PyObjectId = Field(..., description="创建者ID")
    created_at: datetime = Field(default_factory=datetime.utcnow, description="创建时间")
    updated_at: datetime = Field(default_factory=datetime.utcnow, description="更新时间")

    class Config:
        populate_by_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}


class Defect(DefectInDB):
    """缺陷模型"""
    pass